'use client'

import { Comments as CommentsComponent } from 'pliny/comments'
import React, { useEffect, useState, useRef } from 'react'
import { type WalineInstance, type WalineInitOptions, init } from '@waline/client'

import '@waline/client/style'
import siteMetadata from '@/data/siteMetadata'

export type WalineOptions = Omit<WalineInitOptions, 'el'> & { path: string }

export const Waline = (props: WalineOptions) => {
  const walineInstanceRef = useRef<WalineInstance | null>(null)
  const containerRef = React.createRef<HTMLDivElement>()

  useEffect(() => {
    walineInstanceRef.current = init({
      ...props,
      el: containerRef.current,
    })

    return () => walineInstanceRef.current?.destroy()
  }, [])

  useEffect(() => {
    walineInstanceRef.current?.update(props)
  }, [props])

  return <div ref={containerRef} />
}

export default function Comments({ slug }: { slug: string }) {
  const [loadComments, setLoadComments] = useState(false)

  if (!siteMetadata.comments?.provider) {
    return null
  }
  return <Waline {...siteMetadata.comments.waline} slug={slug} />
}
